package net.blogways.ordermgr.user;

import com.asiainfo.bpc.exception.BusiException;
import com.asiainfo.bpc.service.SqlCodeService;
import com.asiainfo.bpc.utils.ToolFactory;
import com.asiainfo.utils.Utils;
import net.blogways.ordermgr.util.Constants;
import net.blogways.ordermgr.util.DBTools;
import net.blogways.ordermgr.util.ErrorCode;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("user:authentication")
public class AuthenticationManager implements Command{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean execute(Context context) throws Exception {
        return false;
    }

    /**
     * 根据用户名查询用户信息
     * @param context
     * @return
     * @throws Exception
     */
    public boolean getUserInfo(Context context)throws Exception{
        String userName = (String) context.get("USER_NAME");
        logger.debug("-------------username:" + userName);

        if (StringUtils.isBlank(userName)){
            throw new BusiException(ErrorCode.USERNAME_NOT_NULL, "用户名不能为空!");
        }

        SqlCodeService sqlCodeService = ToolFactory.getInstance().getSqlCodeService();

        Map param = new HashMap();
        param.put("USER_NAME", userName);
        List users = sqlCodeService.select("SEL_USER_BY_NAME","TD_M_USER", param);

        if (users.size() < 1) {
            return Utils.returnFalseResult(context, ErrorCode.USER_IS_NOT_EXISTS, "该账号不存在.");
        }

        Map userMap = (Map) users.get(0);

        String userStatus = userMap.get("USER_LOCKED").toString();

        if (Constants.USER_LOCKED.equals(userStatus)){
            return Utils.returnFalseResult(context, ErrorCode.USER_IS_LOCKED, "该账号被锁定,无法登录.");
        }

        param.clear();
        param.put("VDICT_CODE", userMap.get("USER_TYPE"));
        param.put("VDICT_TYPE_CODE", "userType");
        param.put("VLOCALE", "zh");
        List names = sqlCodeService.select("SEL_TD_S_DATA_DICT_NAME_BY_CODE", "TD_S_DATA_DICT", param);
        if (names.size() != 1){
            return Utils.returnFalseResult(context, ErrorCode.DATA_ERROR, "类型配置有误，请联系管理员！");
        }
        Map typeName = (Map) names.get(0);
        userMap.put("USER_TYPE_NAME", typeName.get("TYPE_NAME"));
        return Utils.returnOk(context, users, 0);
    }

    /**
     * 查询用户权限 0.菜单权限，1.操作权限
     * @param context
     * @return
     * @throws Exception
     */
    public boolean getUserPermission(Context context) throws Exception {
        String userName = (String) context.get("USER_NAME");
        String permissionType = (String) context.get("PERMISSION_TYPE");
        if (StringUtils.isBlank(userName)) {
            return Utils.returnFalse(context, ErrorCode.USERNAME_NOT_NULL, "用户名不能为空.");
        }

        Map sqlParams = new HashMap();
        List permissions = new ArrayList();
        sqlParams.put("VUSER_NAME", userName);
        sqlParams.put("VPERMISSION_TYPE", permissionType);
        if ("0".equals(permissionType)) {
            permissions = ToolFactory.getInstance().getSqlCodeService().select("SEL_MENU_BY_USER", "TD_S_SYSTEMMENU", sqlParams);
        } else if ("1".equals(permissionType)) {
            permissions = ToolFactory.getInstance().getSqlCodeService().select("SEL_PERMISSION_BY_USER_NAME", "TD_M_PERMISSION", sqlParams);
        }
        return Utils.returnOk(context, permissions);
    }

    /**
     * 获取用户角色
     * @param context
     * @return
     * @throws Exception
     */
    public boolean getUserRole(Context context)throws Exception{
        String userName = (String) context.get("USER_NAME");
        Map sqlParams = new HashMap();
        if (StringUtils.isBlank(userName)) {
            return Utils.returnFalse(context, ErrorCode.USERNAME_NOT_NULL, "用户名不能为空.");
        }
        sqlParams.put("VUSER_NAME", userName);
        List roles = ToolFactory.getInstance().getSqlCodeService().select("SEL_ROLE_BY_USER_NAME", "TD_M_USER_ROLE", sqlParams);
        return Utils.returnOk(context, roles);
    }

    /**
     * 更新用户登录时间
     * @param context
     * @return
     * @throws Exception
     */
    public boolean updateLoginTime(Context context) throws Exception {
        Map sqlParams = new HashMap();
        sqlParams.put("VUSER_NAME", context.get("USER_NAME"));
        int count = ToolFactory.getInstance().getSqlCodeService(Constants.DATABASE_CEN).update("UPDATE_LOGIN_TIME","TD_M_USER", sqlParams);
        logger.debug("------->i:" + count);
        return Utils.returnOkResult(context, "更新成功！");
    }

    /**
     * 查询用户密码.
     *
     * @param context
     * @return
     */
    public boolean queryPassword(Context context) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT USER_NAME,`PASSWORD` FROM TD_M_USER")
                .append("\n WHERE USER_NAME=:VUSER_NAME AND NOW() BETWEEN START_DATE AND END_DATE AND `PASSWORD`=:VPASSWORD;");

        List list = ToolFactory.getInstance().getSqlCodeService(Constants.DATABASE_CEN).select(sql.toString(), DBTools.parameterize(context));
        return Utils.returnOk(context, list, 0);
    }

    public boolean modifyPassword(Context context) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE TD_M_USER ")
                .append("\nSET `PASSWORD` =:VNEW_PASSWORD,`UPDATE_USER_NAME`=:VUPDATE_USER_NAME,`UPDATE_TIME`=NOW()\n")
                .append("WHERE USER_NAME=:VUSER_NAME AND NOW() BETWEEN START_DATE AND END_DATE;");

        int count = ToolFactory.getInstance().getSqlCodeService(Constants.DATABASE_CEN).update(sql.toString(),DBTools.parameterize(context));
        if (count != 1) {
            return Utils.returnFalseResult(context, "E010", "修改用户密码");
        } else {
            return Utils.returnOk(context, new ArrayList(), 0);
        }
    }
}
